export function debounce(func, delay) {
  let timer

  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

/**
 * Created by qiao on 2018/5/30.
 */
/* 选择图生成转换成base64 */
;(function(){
  /*
   ImgCompress({
       id:'uploadImageId', // 上传文件的id
       maxWidth:"1000",  //限制最大宽度或者高度
       success:(base64)=>{
          //base64  压缩成功后的base64
       }
   });
  * */
  var defaults = {
    maxWidth:1000, // 图片在的最大宽度 = 最大高度
    opacity:1, // 图片转化的清晰度
    type:'image/jpeg', // 图片类型
    id:'fileId'
  };
  var ImgCompress = function(options){
    var options = Object.assign(defaults,options);
    ImgCompress.prototype.init(options);
  };
  ImgCompress.prototype = {
    init:function(options){
      var self = this;
      var canvas = this.createCanvas();
      this.changeEvent(this.$(options.id),function(){
        var file = self.$(options.id).files[0];
        self.base64(file,canvas,options,function(data){
          options.success(data,);
        });
      })
    },
    createCanvas:function(){ // create canvas
      var canvas = document.getElementById('ImgCompressCanvas');
      if(!canvas){
        var canvasTag = document.createElement('canvas');
        canvasTag.setAttribute('id','ImgCompressCanvas');
        canvasTag.setAttribute('style','display:none;');
        document.body.appendChild(canvasTag);
        canvas = document.getElementById('ImgCompressCanvas');
      }
      return canvas;
    },
    imgScaleW:function(maxWidth,width,height){
      var imgScale = {};
      var w = 0;
      var h = 0;
      if(width <= maxWidth && height <= maxWidth){
        imgScale = {
          width:width,
          height:height
        }
      }else{
        if(width >= height){
          w = maxWidth;
          h = Math.ceil(maxWidth * height / width);
        }else{
          h = maxWidth;
          w = Math.ceil(maxWidth * width / height);
        }
        imgScale = {
          width:w,
          height:h
        }
      }
      return imgScale;
    },
    base64:function(file,canvas,options,callback){
      var reader = new FileReader();
      var image = new Image();
      var canvas = canvas;
      var ctx = canvas.getContext("2d");
      var self = this;
      reader.onload = function(){
        var result = this.result;
        image.onload = function(){
          var imgScale = self.imgScaleW(options.maxWidth,this.width,this.height);
          canvas.width = imgScale.width;
          canvas.height = imgScale.height;
          ctx.drawImage(image,0,0,imgScale.width,imgScale.height);
          var dataURL = canvas.toDataURL(options.type,options.opacity);
          ctx.clearRect(0,0,imgScale.width,imgScale.height);
          document.getElementById(options.id).value = '';   //清空input  file
          callback(dataURL);
        };
        image.src = result;
      };
      reader.readAsDataURL(file);
    },
    changeEvent:function(id,callback){
      id.addEventListener('change',callback,false);
    },
    $:function(id){
      return document.getElementById(id);
    }
  }
  window.ImgCompress = ImgCompress;
})();
;(function($){ // 弹出框
  /*
  * $.ConfirmBox({
       msg:'提示语',
       confirm:()=>{	// 确定调用方法

       },
       cancel:()=>{	// 取消调用方法

       }
   });
  * */
  var defaults = {
    confirm:function(){}, // 确定调用方法
    cancel:function(){}, // 取消调用方法
    confirmBtn:{ // 确定按钮文本和背景
      text:'确定',
      background:'#fff'
    },
    cancelBtn:{ // 取消按钮文本和背景
      text:'取消',
      background:'#fff'
    },
    isCancel:true, // 是否显示取消按钮
    msg:'' // 提示文字
  };
  var ConfirmRe = function(options){
    this.init(options);
  };
  ConfirmRe.prototype = {
    init:function(options){
      var self = this;
      $('body').append(this.createTags(options));

      $('.promitConfirmButton').on('click',function(ev){
        $(this).parents('.promitMsgLayerList').remove();
        options.confirm();
      });
      if(options.isCancel) { // 是否有取消按钮
        $('.promitCancleButton').on('click',function(ev){
          $(this).parents('.promitMsgLayerList').remove();
          options.cancel();
        });
      }
    },
    createTags:function(options){
      var tags = '<div class="promitMsgLayerList">';
      tags +=				'<div class="promitList">';
      tags +=					'<p>'+ options.msg +'</p>';
      tags +=					'<div style="display:flex; width:100%; justify-content:center; align-items:center;">';
      tags +=						'<div class="promitConfirmButton" style="background:'+ options.confirmBtn.background +';">'+ options.confirmBtn.text +'</div>';
      if(options.isCancel){ // 是否有取消按钮
        tags +=					'<div class="promitCancleButton" style="background:'+ options.cancelBtn.background +';">'+ options.cancelBtn.text +'</div>';
      }
      tags +=					'</div>';
      tags +=				'</div>';
      tags +=			'</div>';
      return tags;
    }
  };
  $.ConfirmBox = function(options){
    var options = $.extend({},defaults,options);
    new ConfirmRe(options);
  };
})(jQuery);

let utils = {
  // toast
  /*
  toast({
      msg:'提示语',
      delay:'显示时间ms为单位'
      });
  * */
  toast: function(data){
    var data = data || {};
    var prompt_st = null;
    var prompt = $('#promptMsg');

    if(prompt.length == 0){
      var tags = '<div id="promptMsg"><span class="prom"></span></div>';
      $('body').append(tags);
      prompt = $('#promptMsg');
    }
    var	prompt = prompt;
    prompt.css({
      position:'fixed',
      top:'0',
      left:'0',
      width:'100%',
      height:'100%',
      'z-index':'1000',
      display:'flex',
      'justify-content':'center',
      'align-items':'center',
      background:'rgba(0,0,0,0)',
    }).find('.prom').css({
      padding:'10px 20px',
      background:'rgba(0,0,0,0.8)',
      color:'#fff',
      opacity:'0',
      'font-size':'14px',
      'max-width':'80%',
      'border-radius':'8px',
    });

    prompt.find('.prom').html(data.msg).animate({
      opacity:'1'
    },500);
    prompt_st = setTimeout(function(){
      prompt.find('.prom').animate({opacity:'0'},500,function(){
        $(this).parent().remove();
        clearTimeout(prompt_st);
      });
    },data.delay || 2000);
  },
  getQueryString:function(name) { // 获取url的参数
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    if (window.location.href.split("?")[1] != undefined) {
      var r = window.location.href.split("?")[1].match(reg);
      if (r == undefined && window.location.href.split("?").length > 2) {
        r = window.location.href.split("?")[2].match(reg);
      }
      if (r != null) return decodeURI(r[2]);
      return null;
    }
  },
  portrait:function(value,defaultImg){ // 背景图片 url()
    var img = '';
    var portrait = '#eee' || 'url(' + img + ') no-repeat 0% 0% / cover';
    var value = value || '';
    var url = (value.indexOf('http') != -1) ? value : (config.domain + value);
    return (!value || value == '') ? portrait : ('url(' + url + ') no-repeat center center / cover');
  },

};
export default utils;
